15. Exercise: Add Binding Adapters

L7 27 Using DataBinding In A RecyclerView SC

Now it’s your turn to complete this exercise yourself!

In this exercise you'll create binding adapters and move data binding to logic to XML.

When you've completed this exercise you will have refactored the SleepNightAdapter to use DataBinding, and replaced bind.

  1. In BindingUtils, define three Binding Adapters, one for each view in list_item_sleep_night:

    For the ImageView, move the code from SleepNightAdapter.ViewHolder bind() function into an extension function:

    @BindingAdapter("sleepImage")
    fun ImageView.setSleepImage(item: SleepNight) {
         setImageResource(when (item.sleepQuality) {
             0 -> R.drawable.ic_sleep_0
             1 -> R.drawable.ic_sleep_1
             2 -> R.drawable.ic_sleep_2
             3 -> R.drawable.ic_sleep_3
             4 -> R.drawable.ic_sleep_4
             5 -> R.drawable.ic_sleep_5
             else -> R.drawable.ic_sleep_active
        })
    }

    For the two TextViews, convert the data to formatted text using the functions provided in Util.kt:

    @BindingAdapter("sleepDurationFormatted")
    fun TextView.setSleepDurationFormatted(item: SleepNight?) {
         item?.let {
             text = convertDurationToFormatted(item.startTimeMilli, item.endTimeMilli,context.resources)
         }
    }
    
    @BindingAdapter("sleepQualityString")
    fun TextView.setSleepQualityString(item: SleepNight?) {
         item?.let {
             text = convertNumericQualityToString(item.sleepQuality, context.resources)
         }
    }


  2. Replace the code in SleepNightAdapter.ViewHolder.bind with a single binding to the SleepNight item, followed by executePendingBindings():

binding.sleep = item
binding.executePendingBindings()


  1. In list_item_sleep_night, add attributes to bind the views to the adapters you created in BindingAdapters:

    For example, for the ImageView, add app:sleepImage="@{sleep}"


  2. Build and run your code.

If you want to start at this step, you can download this exercise from: Step.09-Exercise-Add-Binding-Adapters.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here: Step.09-Solution-Add-Binding-Adapters, or using this git diff.

Task Description:

Complete these tasks to use binding adapters in the ViewHolder.

Task List:

Task Feedback:

Congrats! You've finished implementing data binding in your RecyclerView Adapter and used a DataBinding Adapter!

Reference Documentation